/**
 * created by zhouli on 2019/1/9
 * 展示权限策略下面的人员，通过策略 id 查询
 * 人员---表格（需要单独查询）,只有当策略类型为 USER的时候
 * 部门---显示一个图
 * 公司---显示一个图
 * 全部---显示一个图
 */
import React from 'react';
import {connect} from 'react-redux';
import {Icon, Button, Form, Input, Table, Popover, Popconfirm} from 'antd';
import {messages, superThrottle, getSubText} from "share/common";
import ROService from 'containers/permission-setting/role-permission-setting/role-permission-detail/components/permission-person/permission-person.service';
import 'styles/permission-setting/role-permission-setting/role-permission-detail/components/permission-person/permission-person.scss';
//需要在这个里面去配置弹窗类型
import chooserData from 'share/chooserData';
import ListSelector from 'components/list-selector.js';
import allPerson from 'images/permission-setting/all_person.png';
import ExportModal from 'components/template/export-modal/export-modal'
import ImportModal from 'components/template/import-modal-ie/import-modal'
import config from 'config';

class PermissionPerson extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      keywordUserName: '',
      saving: false,
      data: [],
      showListSelector: false,
      pagination: {
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      columns: [
        {
          title: messages('permission-setting.key69')/*姓名*/,
          key: "userName",
          dataIndex: 'userName',
          width: '16%',
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('common.user.id')/*工号*/,
          key: "employeeID",
          dataIndex: 'employeeID',
          width: '8%',
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('common.department')/*部门*/,
          key: "departmentName",
          dataIndex: 'departmentName',
          width: '10%',
          render: desc => <span><Popover content={desc}
                                         overlayStyle={{width: 200}}
          >{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages("common.operation"),
          key: 'operation',
          width: '15%',
          render: (text, record) => (
            <span>
                  <Popconfirm onConfirm={(e) => this.deleteUserFromGroup(e, record)}
                              title={messages("common.confirm.delete", {controlRule: record.controlRuleName})}>{/* 你确定要删除organizationName吗 */}
                    <a onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                    }}>{messages("common.delete")}</a>
                  </Popconfirm>
                </span>)
        },
      ],
      //点击添加条件中的项目弹窗
      extraParams: {//弹窗额外的参数
        // status: "1001"
      },
      selectorItem: chooserData['user_permission'],//弹窗显示配置
    }
  }

  componentDidMount() {
    if (this.props.policyData.authorizationType === "USER") {
      this.getPersonList();
    }
  }

  getPersonList = () => {
    this.setState({
      loading: true,
    });
    const {pagination, keywordUserName} = this.state;
    let params = {
      policyId: this.props.policyData.id,
      keyword: keywordUserName,
      page: pagination.page,
      size: pagination.pageSize
    };
    ROService.getPolicyDetailPersons(params)
      .then(res => {
        pagination.total = Number(res.headers['x-total-count']);
        this.setState({
          loading: false,
          data: res.data,
          pagination
        })
      })
  };
  //搜索成本中心项的人
  emitEmptyForDep = () => {
    this.userNameInput.focus();
    this.setState({keywordUserName: ''}, () => {
      this.onChangeUserName();
    });
  };
  //节流函数
  onChangeSetUserDepName = superThrottle(() => {
    this.onChangeUserName();
  }, 500, 3000);
  //为了节流函数
  onInputUserDepName = (e) => {
    this.setState({keywordUserName: getSubText(e.target.value,100)});
  };
  //搜索成本中心项的人
  onChangeUserName = (e) => {

    const {pagination} = this.state;
    pagination.page = 0;
    this.setState({
      pagination,
      loading: true,
    }, () => {
      //搜索
      this.getPersonList();
    });
  };
  //添加人员
  handleNew = () => {
    this.setState({showListSelector: true});
  };
  //处理条件添加弹框点击ok,添加值
  handleListOk = (result) => {
    const arr = result.result;
    this.addUserToGroup(arr);
    //关闭弹窗
    this.handleCancel();
  };
  //控制是否弹出条件添加弹窗
  handleCancel = () => {
    this.setState({
      showListSelector: false,
      saving: false
    })
  };

  addUserToGroup(arr) {
    const users = [];
    arr.map(function (item) {
      users.push(item.id);
    });
    let param = {
      policyId:this.props.policyData.id,
      body: users,
    };
    ROService.addPolicyDetailPersonBatch(param)
      .then(() => {
        this.getPersonList();
      });
  }
  deleteUserFromGroup = (e, record) => {
    let param = {
      detailId: record.id
    };
    ROService.deletePolicyDetailPerson(param)
      .then(() => {
        this.getPersonList();
      })
  };
  // 分页点击
  onChangePager = (_pagination) => {
    let pagination = this.state.pagination;
    pagination.page = _pagination.current - 1;
    this.setState({
      pagination
    }, () => {
      this.getPersonList();
    })
  };


  //如果策略类型是USER
  renderUserType = () => {
    const {
      data, loading, saving, pagination, columns,
      showListSelector, extraParams, selectorItem
    } = this.state;
    let policyId = this.props.policyData.id;
    const suffix = this.state.keywordUserName ? <Icon type="close-circle"
                                                      onClick={this.emitEmptyForDep}/> : null;
    return (<div className='user-type-wrap'>
      <div className="table-header">
        <div className="table-header-title">
          {messages('common.total', {total: `${pagination.total || 0}`})/*共搜索到 {total} 条数据*/}
        </div>
        <div className="table-header-buttons">
          <div className="f-left">
            <Button type="primary"
                    onClick={this.handleNew}
                    loading={saving}>
              {/*添加*/}
              {messages('common.add')}
            </Button>

            <ImportModal
              hasErrInfo={true}
              buttonName={messages('permission-setting.key98')/*导入授权人员*/}
              uploadUrl={`${config.baseUrl}/api/authorization/policy/detail/user/import?policyId=${policyId}`}
              showErrUrl={`${config.baseUrl}` + "/api/batch/transaction/logs/v2/${transactionOID}"}
              exportErrUrl={`${config.baseUrl}` + "/api/batch/transaction/logs/failed/export/auth/user/${transactionOID}"}
              onCancel={this.getPersonList}
              templates={[{
                downloadName: messages('permission-setting.key99')/*授权人员模板-点击下载*/,
                templateName: messages('permission-setting.key100')/*授权人员模板*/,
                downloadUrl: "/api/authorization/policy/detail/user/template/download",
                downloading: "userLoading"
              }]}
            />
            <ExportModal
              style={{display:'inline-block'}}
              type="btn"
              exportTitle={messages('permission-setting.key101')/*导出授权人员*/}
              exportType="AUTH_USER"
              exportCondition={{
                policyId: this.props.policyData.id
              }}
              exportCommand={"authUser"}/>
          </div>
          <div className="table-header-inp f-right">
            {/*输入姓名或/工号*/}
            <Input
              className='rule-user-name-search'
              key={'rule-UserName-search'}
              placeholder={messages('permission-setting.key70')/*输入姓名或工号*/}
              prefix={<Icon type="search" className='font-disabled'/>}
              suffix={suffix}
              value={this.state.keywordUserName}
              onInput={this.onInputUserDepName}
              onChange={this.onChangeSetUserDepName}
              ref={node => this.userNameInput = node}
            />
          </div>
          <div className="clear"/>
        </div>
      </div>
      <Table columns={columns}
             dataSource={data}
             pagination={pagination}
             loading={loading}
             bordered
             onChange={this.onChangePager}
             size="middle"
             rowKey={(reCode) => {
               return reCode.userOID
             }}
      />
      <ListSelector
        visible={showListSelector}
        onOk={this.handleListOk}
        onCancel={this.handleCancel}
        extraParams={extraParams}
        selectorItem={selectorItem}
      />
    </div>)
  };
  renderAllType = () => {
    return (<div className='all-person-wrap'>
      <img  className='all-person' src={allPerson}/>
      <p className='all-person-text'>{messages('permission-setting.key71')/*适用全部人员*/}</p>
    </div>)
  };
  renderDepType = () => {
    return (<div className='all-person-wrap'>
      <img  className='all-person' src={allPerson}/>
      <p className='all-person-text'>{messages('permission-setting.key72')/*适用部门经理*/}</p>
    </div>)
  };

  renderInter = (policyData) => {
    if (policyData.authorizationType === "USER") {
      return this.renderUserType();
    } else if (policyData.authorizationType === "DEPTMGR"){
      return this.renderDepType();
    }else {
      return this.renderAllType();
    }
  };

  render() {
    return (
      <div className="permission-person-wrap">
        {this.renderInter(this.props.policyData)}
      </div>
    )
  }
}

PermissionPerson.propTypes = {
  policyData: React.PropTypes.any,//授权策略对象
};

PermissionPerson.defaultProps = {
  policyData: {}
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(Form.create()(PermissionPerson));
